package cn.shangqizhenshuai.sqiot.Filter;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 *
 * @author SQ
 *
 */
@Component("userLoginMap")
public class UserLoginMap {
	public static Map<String, Date> userlogmap = new HashMap<String, Date>();
	/**
	 * 添加用户
	 *
	 * @return 添加是否成功
	 */
	public boolean putuser(String token) {
		userlogmap.put(token, new Date());
		return true;
	}
	/**
	 * 查询此人是否登陆
	 *
	 * @param token
	 * @return 登陆结果
	 */
	public boolean istokenexistence(String token) {

		boolean containsKey = userlogmap.containsKey(token);
		return containsKey;

	}

	/**
	 * 更新用户存在时间的方法
	 *
	 * @return 更新结果
	 */
	public boolean upuser(String token) {
		userlogmap.put(token, new Date());
		return true;
	}

	/**
	 * 用户登出后删除用户和时间超过5分钟未操作删除次用户
	 *
	 * @return
	 */
	public boolean deluser(String token) {
		try {
			userlogmap.remove(token);
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	/**
	 * 自动清除5分钟内为操作的用户
	 *
	 * @return
	 */
	@Scheduled(cron = "0/5 * * * * ? ")
	public void autouserdel() {
		Set<String> keySet = this.userlogmap.keySet();
		long currentTimeMillis = new Date().getTime();
		try {
			if (keySet.size() > 0) {
				for (String string : keySet) {
					if (currentTimeMillis - this.userlogmap.get(string).getTime() >= 12060000) {
						this.deluser(string);
					}
				}
			}
		} catch (Exception e) {
		}

	}

}
